package web.admin.shop.product.tabs;


import domain.shop.Product;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;
import service.facade.admin.ShopAdminService;

import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Display page, where admin can select components of products
 */
public final class ComponentProductPanel extends Panel {

    @SpringBean
    private ShopAdminService adminService;
    private static Logger logger = Logger.getLogger(ComponentProductPanel.class.getName());

    public ComponentProductPanel(String id, final Long productId) {
        super(id);

        add(new AbstractProductRelationsPanel("components", productId, new Model<String>("Komponenty produktu")) {

            @Override
            public void onSubmit() {
                Set<Long> componentsOfProduct = new HashSet<Long>();
                for (ProductWrapper productWrapper : wrappedProducts) {
                    if (productWrapper.isCheck()) {
                        componentsOfProduct.add(productWrapper.getProductId());
                    }
                }
                try {
                    adminService.setComponentsOfProduct(productId, componentsOfProduct);
                    info(getLocalizer().getString("saved", this));
                } catch (Exception e) {
                    logger.log(Level.SEVERE, null, e);
                    error(getLocalizer().getString("system.error", this));
                }
            }

            @Override
            boolean isContained(Product product) {
                Set<Product> components = adminService.findProductById(productId).getComponents();
                if (components == null) {
                    return false;
                }
                for (Product componentsOfProduct : components) {
                    if (componentsOfProduct.getId().equals(product.getId())) {
                        return true;
                    }
                }
                return false;
            }
        });
    }


}








